package com.government.item.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.government.app.bo.KeywordSearchBO;
import com.government.app.vo.KeywordSearchVO;
import com.government.article.domain.ArticlePolicy;
import com.government.article.mapper.ArticlePolicyMapper;
import com.government.company.domain.Company;
import com.government.company.mapper.CompanyMapper;
import com.government.item.domain.ExcelDetail;
import com.government.item.mapper.ExcelDetailMapper;
import com.government.item.service.IExcelDetailService;
import com.government.tag.domain.Tag;
import com.government.tag.mapper.TagMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.transaction.annotation.Transactional;
import com.government.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.government.common.utils.PageUtils.startPage;

/**
 * 立项查询Service业务层处理
 *
 * @author system
 * @date 2023-10-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ExcelDetailServiceImpl implements IExcelDetailService {
    @Autowired
    private ExcelDetailMapper excelDetailMapper;
    @Autowired
    private ArticlePolicyMapper articlePolicyMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CompanyMapper companyMapper;

    /**
     * 查询立项查询
     *
     * @param id 立项查询主键
     * @return 立项查询
     */
    @Override
    public ExcelDetail selectExcelDetailById(Long id) {
        return excelDetailMapper.selectExcelDetailById(id);
    }

    /**
     * 查询立项查询列表
     *
     * @param excelDetail 立项查询
     * @return 立项查询
     */
    @Override
    public List<ExcelDetail> selectExcelDetailList(ExcelDetail excelDetail) {
        return excelDetailMapper.selectExcelDetailList(excelDetail);
    }

    /**
     * 新增立项查询
     *
     * @param excelDetail 立项查询
     * @return 结果
     */
    @Override
    public int insertExcelDetail(ExcelDetail excelDetail) {
        excelDetail.setCreateTime(DateUtils.getNowDate());
        return excelDetailMapper.insertExcelDetail(excelDetail);
    }

    /**
     * 修改立项查询
     *
     * @param excelDetail 立项查询
     * @return 结果
     */
    @Override
    public int updateExcelDetail(ExcelDetail excelDetail) {
        excelDetail.setUpdateTime(DateUtils.getNowDate());
        return excelDetailMapper.updateById(excelDetail);
    }

    /**
     * 批量删除立项查询
     *
     * @param ids 需要删除的立项查询主键
     * @return 结果
     */
    @Override
    public int deleteExcelDetailByIds(Long[] ids) {
        return excelDetailMapper.deleteExcelDetailByIds(ids);
    }

    /**
     * 删除立项查询信息
     *
     * @param id 立项查询主键
     * @return 结果
     */
    @Override
    public int deleteExcelDetailById(Long id) {
        return excelDetailMapper.deleteExcelDetailById(id);
    }

    /**
     * 搜索立项
     *
     * @param bo
     * @return 结果
     */
    @Override
    public List<KeywordSearchVO> searchExcelDetailList(KeywordSearchBO bo) {

        List<ArticlePolicy> policyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());
        // 所有政策Map
        Map<Long, ArticlePolicy> allPolicyMap = policyList.stream().collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));

        // 所有父级郑策
        Map<String, List<ArticlePolicy>> allParentPolicyMap = policyList.stream().filter(item -> StrUtil.isNotBlank(item.getParentId())).collect(Collectors.groupingBy(ArticlePolicy::getParentId));

        List<String> companyNameList = Lists.newArrayList();
        if(StrUtil.isNotBlank(bo.getCompanyName())) {
            companyNameList.add(bo.getCompanyName());
        }
        if (StrUtil.isNotBlank(bo.getKeyword())) {
            List<Company> companyList = companyMapper.selectList(
                    Wrappers.<Company>lambdaQuery()
                            .apply("MATCH(name) AGAINST({0} IN BOOLEAN MODE)", bo.getKeyword())
            );
           // List<Company> companyList = companyMapper.selectList(Wrappers.<Company>lambdaQuery().like(Company::getName,bo.getKeyword()));
            for (Company company : companyList) {
                companyNameList.add(company.getName());
                // 根据单位名称（含：曾用名），在平台“项目立项数据库”中查询，查询该单位已立项项目信息
                if (StrUtil.isNotBlank(company.getHistoryName())) {
                    String[] companyNames = company.getHistoryName().split(";");
                    for (String companyName : companyNames) {
                        if (StrUtil.isNotBlank(companyName) && !"无".equals(companyName) && !"-".equals(companyName)) {
                            if (companyName.contains("（")) {
                                companyName = companyName.substring(0, companyName.indexOf("（"));
                            }
                            companyNameList.add(companyName);
                        }
                    }
                }
            }
        }
        bo.setCompanyNameList(companyNameList);

        List<Tag> tagList = tagMapper.selectList(Wrappers.lambdaQuery());
        Map<String, Long> tagNamesMap = tagList.stream().collect(Collectors.toMap(Tag::getName, Tag::getId));
        List<String> tagIds = Lists.newArrayList();
        // 项目类型标签
        if (CollUtil.isNotEmpty(bo.getItemTypes())) {
            for (String itemType : bo.getItemTypes()) {
                Long tagId = tagNamesMap.get(itemType);
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            }
        }
        bo.setTagIds(tagIds);
        // 查询包含子级政策的所有政策
        if (StrUtil.isNotBlank(bo.getPolicyId())) {
            List<String> policyIds = Lists.newArrayList();
            policyIds.add(bo.getPolicyId());
            bo.setPolicyIds(policyIds);
            getAllChildPolicyId(bo.getPolicyId(), policyIds, allParentPolicyMap);
        }
        startPage();
        // todo 字符长度超8字，且公司结尾，才需要查询曾用名
        List<KeywordSearchVO> result = excelDetailMapper.searchExcelDetailList(bo);
        if (CollUtil.isEmpty(result)) {
            return result;
        }
        for (KeywordSearchVO keywordSearchVO : result) {
//            keywordSearchVO.setCategoryId(Long.parseLong(bo.getPolicyId()));
//            keywordSearchVO.setCategory(allPolicyMap.get(Long.parseLong(bo.getPolicyId())).getName());
            ArticlePolicy articlePolicy = allPolicyMap.get(keywordSearchVO.getCategoryId());
            if (Objects.nonNull(articlePolicy)) {
                keywordSearchVO.setCategory(articlePolicy.getName());
                keywordSearchVO.setCategoryId(articlePolicy.getArticleId());
            }
            StringBuffer address = new StringBuffer();
            if (StrUtil.isNotBlank(keywordSearchVO.getProvinceName())) {
                address.append(keywordSearchVO.getProvinceName());
            }
            if (StrUtil.isNotBlank(keywordSearchVO.getCityName())) {
                address.append("/").append(keywordSearchVO.getCityName());
            }
            if (StrUtil.isNotBlank(keywordSearchVO.getDistrictName())) {
                address.append("/").append(keywordSearchVO.getDistrictName());
            }
            keywordSearchVO.setAddress(address.toString());
        }

//        Set<String> projectList = new HashSet<>();
//        for (KeywordSearchVO keywordSearchVO : result) {
//            projectList.add(keywordSearchVO.getProject());
//        }
//        List<ExcelDetail> excelDetailList = excelDetailMapper.selectList(Wrappers.<ExcelDetail>lambdaQuery()
//                .select(ExcelDetail::getCategory, ExcelDetail::getProject)
//                .in(ExcelDetail::getProject, projectList).groupBy(ExcelDetail::getProject));
//        Map<String, ExcelDetail> excelDetailMap = excelDetailList.stream().collect(Collectors.toMap(ExcelDetail::getProject, x -> x));
//        for (KeywordSearchVO keywordSearchVO : result) {
//            ExcelDetail excelDetail = excelDetailMap.get(keywordSearchVO.getProject());
//            if (StrUtil.isNotBlank(bo.getPolicyId())) {
//                keywordSearchVO.setCategoryId(Long.parseLong(bo.getPolicyId()));
//                keywordSearchVO.setCategory(allPolicyMap.get(Long.parseLong(bo.getPolicyId())).getName());
//            } else {
//                if (Objects.nonNull(excelDetail)) {
//                    if (StrUtil.isNotBlank(excelDetail.getCategory())) {
//                        if (!excelDetail.getCategory().contains(",")) {
//                            setTopPolicy(keywordSearchVO, allPolicyMap, excelDetail.getCategory());
//                        }
//                    }
//                }
//            }
//            StringBuffer address = new StringBuffer();
//            if (StrUtil.isNotBlank(keywordSearchVO.getProvinceName())) {
//                address.append(keywordSearchVO.getProvinceName());
//            }
//            if (StrUtil.isNotBlank(keywordSearchVO.getCityName())) {
//                address.append("/").append(keywordSearchVO.getCityName());
//            }
//            if (StrUtil.isNotBlank(keywordSearchVO.getDistrictName())) {
//                address.append("/").append(keywordSearchVO.getDistrictName());
//            }
//            keywordSearchVO.setAddress(address.toString());
//
//        }
        return result;
    }

    private void getAllChildPolicyId(String articleId, List<String> policyIds, Map<String, List<ArticlePolicy>> allParentPolicyMap) {
        List<ArticlePolicy> articlePolicyList = allParentPolicyMap.get(articleId);
        if (CollUtil.isNotEmpty(articlePolicyList)) {
            for (ArticlePolicy policy : articlePolicyList) {
                String policyId = String.valueOf(policy.getArticleId());
                policyIds.add(policyId);
                getAllChildPolicyId(policyId, policyIds, allParentPolicyMap);
            }
        }
    }

    private void setTopPolicy(KeywordSearchVO keywordSearchVO, Map<Long, ArticlePolicy> allPolicyMap, String policyId) {
        ArticlePolicy articlePolicy = allPolicyMap.get(Long.parseLong(policyId));
        if (Objects.nonNull(articlePolicy)) {
            if (StrUtil.isBlank(articlePolicy.getParentId())) {
                keywordSearchVO.setCategory(articlePolicy.getName());
                keywordSearchVO.setCategoryId(articlePolicy.getArticleId());
            } else {
                setTopPolicy(keywordSearchVO, allPolicyMap, articlePolicy.getParentId());
            }
        }
    }

}
